package com.fr.chicken.manager.vip;

import com.fr.chicken.dao.VipConfigureDao;
import com.fr.chicken.manager.house.HouseManager;
import com.fr.chicken.manager.message.MessageManager;
import com.fr.chicken.manager.playerinfo.PlayerInfoManager;
import com.fr.chicken.model.PlayerInfo;
import com.fr.chicken.model.VipConfigure;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class VipManager {

    @Autowired
    private  HouseManager houseManager;
    @Autowired
    private PlayerInfoManager playerInfoManager;
    @Autowired
    private MessageManager messageManager;
    @Autowired
    private VipConfigureDao vipConfigureDao;
    /**
     * 更新VIP等级
     * */
    public void updataVip(long playerId,int activationNum){
        // 根据激活码的数量找到对应的vip等级
        int upVipLv = queryActivationNumCorrespondingVipLV(activationNum);
        PlayerInfo player = playerInfoManager.findPlayerInfoById(playerId);
        if(player == null){
           return;
        }
        boolean  isUp = false;
        synchronized (player){
            if(player.getVip() < upVipLv){
                player.setVip(upVipLv);
                playerInfoManager.savePlayerInfo(player);
                isUp = true;
            }
        }
        // 发送vip升级奖励
        if(isUp){
            sendVipAward(playerId,player.getVip());
        }
    }

    private void sendVipAward(long playerId,int vipLv){
        int chickenNum = getVipAward(vipLv);
        houseManager.addChickens(playerId,(byte)3,chickenNum);
        messageManager.sendSystemMessage(playerId,chickenNum,String.format("升级到VIP%d,赠送%d只生态鸡",vipLv,chickenNum));
    }

    /**
     * vip等级对应的推荐人数
     * */
    private int queryActivationNumCorrespondingVipLV(int activationNum){
        int level = vipConfigureDao.selectByTeamNum(activationNum);
        if (level!=0){
            return level;
        }
        return 0;
    }

    /**
     * vip奖励的鸡数量
     * */
    private int getVipAward(int vipLv){
        VipConfigure vipConfigure = vipConfigureDao.selectByLevel(vipLv);
        if (vipConfigure==null){
            return 0;
        }
        return vipConfigure.getGiveNum();
    }
}
